package com.example.demo.demos.web;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/web")
public class UserController {
    public List<User> user = new ArrayList<>();
    {
        user.add(new User("张三",19,"123456789@qq.com"));
        user.add(new User("李四",21,"12389@qq.com"));
    }
    @GetMapping("/all")
    public ResponseEntity<List<User>> getAll(){
        return ResponseEntity.ok(user);
    }
    @GetMapping("/{id}")
    public ResponseEntity<User> getOne(@PathVariable int id){
        if (id > 0 && id <= user.size()){
            User user1 = user.get(id-1);
            return ResponseEntity.ok(user1);
        }
        else {
            return ResponseEntity.notFound().build();
        }
    }
    @PostMapping("/add")
    public ResponseEntity<User> setadd(@RequestBody User user1){
        user.add(user1);
        return ResponseEntity.ok(user1);
    }
    @PutMapping("/{id}")
    public ResponseEntity<User> update(@RequestBody User user1,@PathVariable int id){
        if(id > 0 && id <= user.size()){
            user.set(id-1,user1);
            return ResponseEntity.ok(user1);
        }
        else {
            return ResponseEntity.notFound().build();
        }
    }
    @DeleteMapping("/{id}")
    public ResponseEntity<User> delete(@PathVariable int id){
        if(id > 0 && id <= user.size()){
            user.remove(id-1);
            return ResponseEntity.noContent().build();
        }
        else {
            return ResponseEntity.notFound().build();
        }
    }
}
